package com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.strategy.in;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.SpringContextBaseHolder;
import com.wxy.ej.flow.modules.taskflow.bean.TaskFlowDs;
import com.wxy.ej.flow.modules.taskflow.dto.DataDto;
import com.wxy.ej.flow.modules.taskflow.dto.NodeDto;
import com.wxy.ej.flow.modules.taskflow.repository.JdbcRepository;
import com.wxy.ej.flow.modules.taskflow.service.beanService.TaskFlowDsService;
import com.wxy.ej.flow.modules.taskflow.service.ds.MysqlUtils;
import com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.NodeStrategy;
import com.wxy.ej.flow.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class InJdbcStrategy extends NodeStrategy {

    @Override
    public Result action(NodeDto node, JSONObject flowDataJson, DataDto dataDto)  throws Exception{
        log.info("InJdbcStrategy: ");

        Long dataSourceId = node.getDataSourceId();
        String sql = node.getSql();

        // 验证
        if (sql==null) {
            return Result.builder().fault("sql is null");
        }

        // 正则从sql script中, 取${item.id}
        String pattern = "\\$\\{[\\w.}\\[\\]]*";
        List<String> jsScriptList = RegexUtils.searchMatch(sql, pattern,0);
        // 执行js取值
        Map<String, Object> jsResultMap = new HashMap<>();
        for (String jsScript:jsScriptList) {
            String jsScript2 = jsScript.substring(2, jsScript.length()-1);
            Object o = executeScriptForResult(dataDto, jsScript2);
            jsResultMap.put(jsScript, o);
        }

        // replace sql script
        List<Object> paramList = new ArrayList<>();
        for (String key:jsScriptList) {
            sql = sql.replace(key, "?");
            paramList.add(jsResultMap.get(key));
        }

        // log
        dataDto.getLogList().add(sql);
        dataDto.getLogList().add(JSONArray.toJSONString(paramList));

        // 取当前数据源执行sql
        List<Map<String, Object>> list = null;
        if (dataSourceId==null || dataSourceId==0l) {
            JdbcRepository jdbcRepository = SpringContextBaseHolder.getBean("jdbcRepository");
            list = jdbcRepository.executeQuery(sql, paramList);
        }
        // 执行新数据源的jdbc
        else{
            list = executeDsSql(dataSourceId, sql, paramList);
        }

        // 保存数据
        //saveInData(node, dataDto, list);
        String inDataToStorageMapVar = node.getDefineVarName();
        dataDto.getStorageDataVarMap().put(inDataToStorageMapVar, list);
        dataDto.getLogList().add("保存数据在"+inDataToStorageMapVar+"里，记录数："+(list!=null?list.size():0));

        return Result.builder(list);
    }

    private List<Map<String, Object>> executeDsSql(Long dataSourceId, String sql, List<Object> paramList) throws SQLException {
        TaskFlowDsService taskFlowDsService = SpringContextBaseHolder.getBean("taskFlowDsService");
        TaskFlowDs taskFlowDs = taskFlowDsService.getById(dataSourceId);
        String type = taskFlowDs.getType();
        if ("mysql".equalsIgnoreCase(type)) {
            return MysqlUtils.queryList(taskFlowDs, sql, paramList);
        }
        return null;
    }


}
